package com.example.util;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description //TODO
 * @Date 2022/9/21 16:19
 * @Author lonng
 **/
public class SandboxRun {
    private static volatile SandboxRun instance;

    private GetCodeUtil getCodeUtil=new GetCodeUtil();

    private PostManUtil postManUtil=new PostManUtil();

    private static final String url="http://192.168.2.71:5050/run";

    public String sendProblem(String language,String requestBody,Integer timeLimit,Integer memoryLimit) {
        requestBody = requestBody.replace('\n', ' ').replace("\"", "\\\"");
        if (language.equals("C++") || language.equals("C")) {
            System.out.println("=========");
            requestBody = requestBody.replace("<iostream>", "<iostream>\\n").replace(";", ";\\n");
        }

//        System.out.println(dataJava);
//        System.out.println(url);
        switch (language) {
            case "Java":
//            System.out.println(postManUtil.sendPost(url,dataJava,"utf-8"));
                return postManUtil.sendPost(url, getCodeUtil.getJava(requestBody,memoryLimit,timeLimit), "utf-8");
            case "C++":
                return postManUtil.sendPost(url, getCodeUtil.getCcc(requestBody,memoryLimit,timeLimit), "utf-8");
            case "C":
                return postManUtil.sendPost(url, getCodeUtil.getC(requestBody,memoryLimit,timeLimit), "utf-8");
            case "Ptthon":
                return postManUtil.sendPost(url, getCodeUtil.getPython(requestBody,memoryLimit,timeLimit), "utf-8");
        }
        return null;
    }


    public String evaluatingProblem(String language,String fileId,
                                    Integer timeLimit, Integer memoryLimit,
                                    Integer stackLimit,String files) {
        System.out.println("====================");
        String code="";
        switch (language){
            case "Java":
                code=getCodeUtil.getJavaCode(fileId,timeLimit,memoryLimit,stackLimit,files);
                break;
            case "C++":
                code=getCodeUtil.getCccCode(fileId,timeLimit,memoryLimit,stackLimit,files);
                break;
        }
        System.out.println(code);
//            System.out.println(postManUtil.sendPost(url,code,"utf-8"));
        return postManUtil.sendPost(url,code,"utf-8");
    }
    public static SandboxRun getInstance(){
        //防止后面的线程再去频繁竞争"锁"
        if(null==instance){//T1,T2 = > null
            synchronized (SandboxRun.class){//T2在等待
                //只能由一个线程进入 - 同步代码块
                //T1进入了...
                if(null==instance){
                    //①申请空间 - 内存地址出来了
                    //②instance = 对象的内存地址 => instance已经不为null
                    //③慢慢调用构造,构造完毕之后,对象是完整的合法的对象.
                    instance = new SandboxRun();
                }
            }
        }
        return instance;
    }

}
